package com.sinosoft.web.common.servlet;

import cn.com.sinux.spring.commons.SystemConfig;
import com.sinosoft.web.common.WebInput;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.servlet.HttpServletBean;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2015/9/16.
 */
public class AttachmentServlet extends HttpServletBean {

    private PathMatcher pathMatcher;

    /**
     * Remember the startup time, using no last-modified time before it.
     */

    protected void initServletBean() {
        this.pathMatcher = getPathMatcher();
    }

    /**
     * Return a PathMatcher to use for matching the "allowedResources" URL pattern.
     * Default is AntPathMatcher.
     *
     * @see org.springframework.util.AntPathMatcher
     */
    protected PathMatcher getPathMatcher() {
        return new AntPathMatcher();
    }


    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String remote = SystemConfig.getProperty("file.remote.url");
        //远程资源访问
        if (StringUtils.isNotBlank(remote)) {
            resp.sendRedirect(remote + req.getPathInfo());
            super.doGet(req, resp);
            return;
        }
        if (getPathMatcher().match("/download/**", req.getRequestURI())) {
            String f = req.getParameter("f");
            if (StringUtils.isNotBlank(f)) {
                f = new String(f.getBytes("ISO8859-1"), "UTF-8");
            }
            new WebInput(req).getWebOutput(resp).sendFile(SystemConfig.getProperty("trunk.root.path") + req.getPathInfo(), f);
        } else if (getPathMatcher().match("/play/**", req.getRequestURI())) {
            new WebInput(req).getWebOutput(resp).sendFile(SystemConfig.getProperty("trunk.root.path") + req.getPathInfo());
        } else {
            new WebInput(req).getWebOutput(resp).sendFile(
                    new File(SystemConfig.getProperty("trunk.root.path") + req.getPathInfo()), null, null, false, false);
        }
//        super.doGet(req, resp);
    }
}
